$NG.AllReady(function (
    editPage,
    { useAction, useValuesChange, useDataIndexChange, useClick }
) {
    const headerTable = $NG.getCmpApi("p_form_ywgcwb_JL")
    const mstform = $NG.getCmpApi("p_form_ywgcwb_JL")
    const dgrid1 = $NG.getCmpApi("p_form_ywgcwb_JL_d1")
    const dgrid2 = $NG.getCmpApi("p_form_ywgcwb_JL_d2")
    const dgrid3 = $NG.getCmpApi("p_form_ywgcwb_JL_d3")
    $NG.updateUI((updater)=>{
        updater.editGrid.p_form_ywgcwb_JL_d3.u_bg_qty.setProps({
            hidden:true
        })
    })
    useValuesChange(async ({args})=>{
        await getPtInfoByPhid()
        await getWgsbD3Qty()
        await getCntIndoByGzdyAndSbqd()
        filterCnt()
      cntDFilter()
    }, "p_form_ywgcwb_JL.phid_pc")
    useValuesChange(async ({args})=>{
        await getCntMInfoByPhid()
        await getWgsbD3Qty()
        setTimeout(()=>{
        getCntIndoByGzdyAndSbqd()
        },300)
    },"p_form_ywgcwb_JL.u_fbht_name")

    useDataIndexChange(({args})=>{
        const row = args[0]
        let total_aty = 0;
        if(window._lsz_catch_qty){
            window._lsz_catch_qty.forEach(item=>{
                if(item.u_fbht_code == row.u_fbht_code){
                    total_aty = item.bq_qty
                }
            })
        }
        row.u_ljjl_qty = (Number(total_aty) || 0) + (Number(row.u_bqjlsl) || 0)
        if(row.u_ljjl_qty>(Number(row.u_bg_qty) || 0)+(Number(row.u_fbsysl_qty) || 0)){
            row.u_ljjl_qty = (Number(total_aty) || 0)
            row.u_bqjlsl = null
            $NG.alert("累计数量已超出")
        }
        dgrid3.refreshView()
    },"u_bqjlsl")



    useDataIndexChange(({args})=>{
        const text = args[0].u_gzdy_name_EXName
        // args[0].u_gzdy_code
        console.log(args[0]);
        if(text){
            for(let key in window._lsz_catch_gzdyData){
                console.log(`发现相同`,key,text);
                if (key == text) {
					dgrid3.addRows(
						window._lsz_catch_gzdyData[key].reduce((value, el) => {
							//计算累计金额
							let total_amt = 0;
							let cnt_qty = 0;
							if (window._lsz_catch_qty) {
								window._lsz_catch_qty.forEach((qty_item) => {
									if (qty_item.u_fbht_code == el.item_no) {
										total_amt = qty_item.bq_qty;
										cnt_qty =
											(Number(el.qty) || 0) -
											(Number(total_amt) || 0);
									}
								});
							}
                            if(!args[0].u_gzdy_code){
                                args[0].u_gzdy_code = el.u_gzdy_code
                                args[0].u_lx = el.u_lx
                            }
							value.push({
								rel_key1: args[0].rel_key1,
								u_sbqd_code: el.u_equipment_list_no,
								u_sbqd_name_EXName: el.u_equipment_list_name,
								u_sbqd_name: el.sbqd_phid,
								u_danw: el.phid_unit,
								u_danw_EXName: el.msname,
								u_fbht_code: el.item_no,
								u_fbqd_name_EXName: el.item_name,
								u_fbqd_name: el.item_phid,
								u_gzdy_code: el.u_gzdy_code,
								u_gzdy_name_EXName: el.u_gzdy_name,
								u_gzdy_name: el.gzdy_phid,
								u_ljjl_qty: total_amt,
								u_fbsysl_qty: el.qty,
                                u_bg_qty:el.u_bg_qty
							});
                            return value
						}, [])
					);
				}
            }
        }
        dgrid2.refreshView()
        dgrid1.refreshView()
        dgrid3.refreshView()
    },"u_gzdy_name")
    //合同信息复位
    function rectCntInfo(){
        $NG.updateState((updater)=>{
            updater.data.p_form_cnt_visa.setProps({
                u_cnt_name:"",
                u_cnt:""
            })
        })
    }
    filterCnt()
    // 过滤合同
    function filterCnt(){
        console.log(`项目id`,headerTable.getItem("phid_pc").getValue());
        if(!headerTable.getItem("phid_pc").getValue()) return 
        $NG.updateUI((updater, state) => {
            console.log('过滤参数检查', updater);
            updater.fieldSetForm.p_form_ywgcwb_JL.u_fbht_name.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = $NG.getCmpApi('p_form_ywgcwb_JL').getItem('phid_pc').getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!headerTable.getItem("phid_pc").getValue() && {
                    clientSqlFilter: {
                        bill_type: 4,//合同类型
                        phid_pc: headerTable.getItem("phid_pc").getValue()
                    }
                }),
            });
        });
    }
    //获取合同信息
    function getCntInfo(){
        $NG.execServer(
            "getCntMInfoByPhid",
            { phid: headerTable.getItem("合同字段").getValue() },//TODO待填充合同字段名
            function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(`合同：`,datas);
                $NG.updateState((updater)=>{
                    updater.data.p_form_ywgcwb_JL.setProps({
                        //TODO 合同编码字段待补充
                        编码:datas.pcm_no,
                        u_fbgys_name:{
                            label:datas.supply_name,
                            value:datas.supply_no
                        },
                        

                    })
                })
            }
        );
    }
    getPtInfoByPhid()
    async function getPtInfoByPhid() {
        if (mstform.getItem("phid_pc").getValue()) {
          await $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log(datas);
            $NG.updateState((updater) => {
              updater.data.p_form_ywgcwb_JL.setProps({
                //项目编码
                u_pc_no: datas.pc_no,
              });
            });
          });
        }
      }
      //获取合同信息
      getCntMInfoByPhid()
      async function getCntMInfoByPhid() {
        await $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_fbht_name").getValue() }, async function (res) {
            console.log(`合同获取`,res,mstform.getItem("u_fbht_name").getValue());
            if(res.count == 0) return
          const datas = JSON.parse(res.data)[0].extendObjects;
          await $NG.updateState((updater) => {
            updater.data.p_form_ywgcwb_JL.setProps({
                u_fbht_bo: datas.pcm_no, //合同编码
              //乙方单位
              u_fbgys_name: { value: datas.supply_id, label: datas.supply_name },
            });
          });
        });
      }
      cntDFilter()
        function cntDFilter() {
        const phid_pcc = $NG.getCmpApi('p_form_ywgcwb_JL').getItem('phid_pc').getValue();
        if(!phid_pcc){
            return 
        }
        $NG.updateUI(updater => updater.editGrid.p_form_ywgcwb_JL_d1.u_gzdy_name.setProps((p) => {
            return {
            ...p, editor: {
                ...p.editor,
                clientSqlFilter: { 'm.phid_pc': $NG.getCmpApi('p_form_ywgcwb_JL').getItem('phid_pc').getValue() },
            }
            };
        }));
        }

      //获取明细
      getCntIndoByGzdyAndSbqd()
      async function getCntIndoByGzdyAndSbqd(){
        const phid_pc = mstform.getItem("phid_pc").getValue()
        const cnt = mstform.getItem("u_fbht_name").getValue()
        const gys = mstform.getItem("u_fbgys_name").getValue()
        if(!phid_pc||!cnt||!gys) return 
        await $NG.execServer("getCntIndoByGzdyAndSbqd",{cnt,phid_pc,gys},async (res)=>{
            console.log(`高级明细匹配`,res);
            if(res.count == 0) return 
            const _data = JSON.parse(res.data)
            let map = {}
            _data.forEach(items=>{
                const item = items.extendObjects
                if(!map[item.u_gzdy_name]){
                    map[item.u_gzdy_name] = [item]
                } else {
                    map[item.u_gzdy_name].push(item)
                }
            })
            console.log(`检查参数信息`,map);

            //缓存数据
            window._lsz_catch_gzdyData = {...map}
            console.log(`缓存的数据`, window._lsz_catch_gzdyData);
            // const d_num = 0
            // for(let key in map){
            //     $NG.getCmpApi("toolbar_p_form_ywgcwb_JL_d1")
			// 		.getItem("addrow")
			// 		.getRef()
			// 		.click();
                    
            // }
            //自动带出逻辑
            // //生成同步延迟
            // const sleep = 500
            // const start = new Date().getTime()+sleep
            // while(new Date().getTime()<start){
            //     //死循环同步
            // }
            // setTimeout(()=>{
            //     const d1rows= dgrid1.getRows()
            //     console.log(d1rows[0],'测试');
            //     let i = 0
            //     for(let key in map){
            //         d1rows[i].u_gzdy_name = map[key][0].gzdy_phid
            //         d1rows[i].u_gzdy_name_EXName = key
            //         console.log(key,map[key]);
            //         map[key].forEach(el => {
            //             //计算累计金额
            //             let total_amt = 0
            //             let cnt_qty = 0
            //             if(window._lsz_catch_qty){
            //                 window._lsz_catch_qty.forEach(qty_item =>{
            //                     if(qty_item.u_fbht_code == el.item_no){
            //                         total_amt = qty_item.bq_qty
            //                         cnt_qty = (Number(el.qty) || 0) - (Number(total_amt) || 0)
            //                     }
            //                 })
            //             }
            //             dgrid3.addRows({
            //                 rel_key1:d1rows[i].rel_key1,
            //                 u_sbqd_code:el.u_equipment_list_no,
            //                 u_sbqd_name:el.u_equipment_list_name,
            //                 u_danw:el.phid_unit,
            //                 u_danw_EXName:el.msname,
            //                 u_fbht_code:el.item_no,
            //                 u_fbqd_name:el.item_name,
            //                 u_gzdy_code:el.u_gzdy_code,
            //                 u_gzdy_name:el.u_gzdy_name,
            //                 u_ljjl_qty:total_amt,
            //                 u_fbsysl_qty:cnt_qty
            //             })
            //         })
            //     }
            //     dgrid1.refreshView()
            //     dgrid2.refreshView()
            // },200)
        
        })
      }
      //获取之前累计的数量，根据合同清单编码分类
      getWgsbD3Qty()
      async function getWgsbD3Qty(){
        const phid_pc = mstform.getItem("phid_pc").getValue()
        const cnt = mstform.getItem("u_fbht_name").getValue()
        if(!cnt||!phid_pc) return 
        $NG.execServer("getWgsbD3Qty",{phid_pc,cnt},(res)=>{
            console.log(`查找历史数量`,res);
            if(res.count == 0) return 
            const _data = JSON.parse(res.data)
            window._lsz_catch_qty = _data.reduce((value,items)=>{
                const item = items.extendObjects
                value.push(item)
                return value
            },[]) 
        })
      }
});